package com.csmp.service.impl;

import java.util.List;

import org.apache.commons.lang.xwork.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.bs.bean.Doc;
import com.csmp.service.AbstractDocService;

public class DocServiceImpl extends AbstractDocService {

	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected List<Doc> findList(Doc searchbean, int first, int max) {
		DetachedCriteria criteria=DetachedCriteria.forClass(CLASS_NAME);
		setContion(searchbean, criteria);
		List<Doc> list=getHibernateTemplate().findByCriteria(criteria,first,max);
		return list;
	}

	protected Doc loadObj(Long id) {
		return (Doc) getHibernateTemplate().get(CLASS_NAME, id);
	}

	protected void delObj(Doc delObj) {
		getHibernateTemplate().delete(delObj);
		
	}

	@SuppressWarnings("unchecked")
	public int getCount(Doc bean) {
		DetachedCriteria criteria=DetachedCriteria.forClass(CLASS_NAME);
		try {
			setContion(bean,criteria);
		} catch (Exception e) {
			e.printStackTrace();
		}
		criteria.setProjection(Projections.rowCount());
		List<Integer> list=getHibernateTemplate().findByCriteria(criteria);
		if(list == null || list.isEmpty()){
			return 0;
		}
		return list.get(0);
	}
	
	
	private void setContion(Doc bean,DetachedCriteria criteria){
		if(StringUtils.isNotBlank(bean.getDocTitle())){
			criteria.add(Restrictions.like("docTitle", bean.getDocTitle(), MatchMode.ANYWHERE));
		}
		
		if(StringUtils.isNotBlank(bean.getDocType())){
			criteria.add(Restrictions.eq("docType", bean.getDocType()));
		}
		
		if(bean.getValidDate() !=null){
			criteria.add(Restrictions.eq("validDate", bean.getValidDate()));
		}
		if(StringUtils.isNotBlank(bean.getDocId())){
			criteria.add(Restrictions.like("docId", bean.getDocId().trim(),MatchMode.ANYWHERE));
		}
		
	}

	protected void saveObj(Doc entity) {
		getHibernateTemplate().saveOrUpdate(entity);
		
	}

}
